﻿#region Usings

using System;
using System.Collections;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Framework;
using DotNetNuke.Security;
using DotNetNuke.Security.Roles;
using DotNetNuke.Security.Roles.Internal;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.WebControls;

using BuRU = VLUNewsBusiness.VLURolesAndUsers;

#endregion

namespace VLUNewsUI.VLURolesAndUsers
{

	/// -----------------------------------------------------------------------------
	/// <summary>
	/// The Roles PortalModuleBase is used to manage the Security Roles for the
	/// portal.
	/// </summary>
    /// <remarks>
	/// </remarks>
	/// <history>
	/// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
	///                       and localisation
	/// </history>
	/// -----------------------------------------------------------------------------
    public partial class Roles : PortalModuleBase, IActionable
    {

        #region Private Members

        private int _roleGroupId = -1;

        #endregion

        #region IActionable Members

        public ModuleActionCollection ModuleActions
        {
            get
            {
                var actions = new ModuleActionCollection
                                  {
                                      {
                                          GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), ModuleActionType.AddContent, "", "add.gif",
                                          EditUrl("RoleGroupID", Request.QueryString["RoleGroupID"]), false, SecurityAccessLevel.Edit, true, false
                                          }
                                      //    ,
                                      //{
                                      //    GetNextActionID(), Localization.GetString("AddGroup.Action", LocalResourceFile), ModuleActionType.AddContent, "", "add.gif", EditUrl("EditGroup"), false,
                                      //    SecurityAccessLevel.Edit, true, false
                                      //    }
                                  };
                return actions;
            }
        }

        #endregion

        #region Private Methods

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// BindData gets the roles from the Database and binds them to the DataGrid
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        ///     [cnurse]    01/05/2006  Updated to reflect Use of Role Groups
        /// </history>
        /// -----------------------------------------------------------------------------
        private void BindData()
        {
            _roleGroupId = BuRU.RoleAndUser.GetNewsRoleGroupID();
            var roles = _roleGroupId < -1 
                                ? TestableRoleController.Instance.GetRoles(PortalId) 
                                : TestableRoleController.Instance.GetRoles(PortalId, r => r.RoleGroupID == _roleGroupId);
            grdRoles.DataSource = roles;

            Localization.LocalizeDataGrid(ref grdRoles, LocalResourceFile);

            grdRoles.DataBind();
        }

        #endregion

		#region "Public Methods"

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// FormatPeriod filters out Null values from the Period column of the Grid
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        public string FormatPeriod(int period)
        {
            var formatPeriod = Null.NullString;
            try
            {
                if (period != Null.NullInteger)
                {
                    formatPeriod = period.ToString(CultureInfo.InvariantCulture);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return formatPeriod;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// FormatPrice correctly formats the fee
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        public string FormatPrice(float price)
        {
            var formatPrice = Null.NullString;
            try
            {
                if (price != Null.NullSingle)
                {
                    formatPrice = price.ToString("##0.00");
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return formatPrice;
        }

		#endregion

		#region Event Handlers

		/// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Init runs when the control is initialised
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            jQuery.RequestDnnPluginsRegistration();

            foreach (DataGridColumn column in grdRoles.Columns)
            {
                if (ReferenceEquals(column.GetType(), typeof (ImageCommandColumn)))
                {
					//Manage Delete Confirm JS
                    var imageColumn = (ImageCommandColumn) column;
                    imageColumn.Visible = IsEditable;
                    if (imageColumn.CommandName == "Delete")
                    {
                        imageColumn.OnClickJS = Localization.GetString("DeleteItem");
                    }
					
                    //Manage Edit Column NavigateURLFormatString
                    if (imageColumn.CommandName == "Edit")
                    {
                        //so first create the format string with a dummy value and then
                        //replace the dummy value with the FormatString place holder
                        string formatString = EditUrl("RoleID", "KEYFIELD", "Edit");
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }
					
                    //Manage Roles Column NavigateURLFormatString
                    if (imageColumn.CommandName == "UserRoles")
                    {
                        //so first create the format string with a dummy value and then
                        //replace the dummy value with the FormatString place holder
                        string formatString = Globals.NavigateURL(TabId, "User Roles", "RoleId=KEYFIELD", "mid=" + ModuleId);
                        formatString = formatString.Replace("KEYFIELD", "{0}");
                        imageColumn.NavigateURLFormatString = formatString;
                    }
					
                    //Localize Image Column Text
                    if (!String.IsNullOrEmpty(imageColumn.CommandName))
                    {
                        imageColumn.Text = Localization.GetString(imageColumn.CommandName, LocalResourceFile);
                    }
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            grdRoles.ItemDataBound += OnRolesGridItemDataBound;

            try
            {
                if (!Page.IsPostBack)
                {
                    if ((Request.QueryString["RoleGroupID"] != null))
                    {
                        _roleGroupId = Int32.Parse(Request.QueryString["RoleGroupID"]);
                    }
                    BindData();
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// grdRoles_ItemDataBound runs when a row in the grid is bound
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	11/28/2008 Created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnRolesGridItemDataBound(object sender, DataGridItemEventArgs e)
        {
            var item = e.Item;
            switch (item.ItemType)
            {
                case ListItemType.SelectedItem:
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    {
                        var imgColumnControl = item.Controls[0].Controls[0];
                        if (imgColumnControl is HyperLink)
                        {
                            var editLink = (HyperLink) imgColumnControl;
                            var role = (RoleInfo) item.DataItem;
                            editLink.Visible = role.RoleName != PortalSettings.AdministratorRoleName || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName));
                        }
                        imgColumnControl = item.Controls[1].Controls[0];
                        if (imgColumnControl is HyperLink)
                        {
                            var rolesLink = (HyperLink) imgColumnControl;
                            var role = (RoleInfo) item.DataItem;
                            rolesLink.Visible = (role.Status == RoleStatus.Approved) && (role.RoleName != PortalSettings.AdministratorRoleName || (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName)));
                        }
                    }
                    break;
            }
        }

        #endregion

    }
}